package com.irixel.hdc.controllers;

import java.security.Principal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import com.irixel.hdc.dto.BeneficiarioDTO;

@Controller
public class BeneficiarioController {
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	public @ResponseBody List<BeneficiarioDTO> getBeneficiarios(Principal principal){		
		final Long userId = jdbcTemplate.queryForLong(
				"select id from users where username = ?", principal.getName());
		
		List<BeneficiarioDTO> ret = jdbcTemplate
				.query("select * from beneficiario where id_user = ?",
						new Object[] { userId },
						new RowMapper<BeneficiarioDTO>() {

							@Override
							public BeneficiarioDTO mapRow(ResultSet rs, int rowNum)
									throws SQLException {
								BeneficiarioDTO ret = new BeneficiarioDTO();
								ret.setIdUser(userId);
								ret.setNombre(rs.getString("nombre"));
								ret.setRut(rs.getString("rut"));
								ret.setTelf(rs.getString("telf"));

								return ret;
							}

						});
		
		return ret;
	}
	
}
